//
//  GeneralManagerViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 9/26/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "GeneralManagerViewController.h"

@interface GeneralManagerViewController ()
{
    CustomAlertView *alertView;
    PayHistoryAlertView *payHistoryAlertView;
}
@end

@implementation GeneralManagerViewController

@synthesize scrollView;
@synthesize backButton;
@synthesize popUpView;
@synthesize popUpViewHistory;
@synthesize popUpViewHistoryFinished;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"General", @"General");
        self.tabBarItem.image = [UIImage imageNamed:@"icon-money.png"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    //------------------------Init Table View-----------------------------//
    //------Data Section Key : Key for group of expense and income 
    dateSectionKey = [[NSMutableArray alloc]init];
    //------Income Expense Dictionary : Dictionary With Two Array Expense and Icome Group by their day key----//
    
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDate *date = [NSDate date];
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                     fromDate:date];
    [comps setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    today = [cal dateFromComponents:comps];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *weekdayComponents     = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

    NSDateComponents *componentsToSubtract  = [[NSDateComponents alloc] init];
    [componentsToSubtract setDay: (0 - [weekdayComponents weekday]) + 2];
    [componentsToSubtract setHour: 0 - [weekdayComponents hour] + 7];
    [componentsToSubtract setMinute: 0 - [weekdayComponents minute]];
    [componentsToSubtract setSecond: 0 - [weekdayComponents second]];
    
    firstDayOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
    NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:firstDayOfWeek];
    [componentsToAdd setDay:6];
    endDayOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:firstDayOfWeek options:0];
    
    NSLog(@"Today is %@ | Monday is %@ | Sunday is %@", today, firstDayOfWeek, endDayOfWeek);
    
    //Get Income and Expense Array
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    expenseRowNumber = [expenseArray count];

    //Get Loan and Debt Array
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    loanRowNumber = [loanArray count]; 
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    debtRowNumber = [debtArray count];
    
    loanCompletedArray = [[NSMutableArray alloc] init];
    debtCompletedArray = [[NSMutableArray alloc] init];
    
    //Get Loan History 
    
    for (Loan *tempLoan in loanArray) {
        double loanCompleted = 0;
        NSArray *tempLoanHistoryArray = [DataBaseAccess getAllLoanHistoryInLoan:tempLoan];
        if ([tempLoanHistoryArray count] > 0) {
            for (LoanHistory *loanHistory in tempLoanHistoryArray) {
                loanCompleted += [loanHistory.lh_amount doubleValue];
            }
            [loanCompletedArray addObject:[NSNumber numberWithDouble:loanCompleted]];
        } else {
            [loanCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
        
    }
    
    for (NSNumber *number in loanCompletedArray) {
        NSLog(@"K LOAN: %0.2f", [number doubleValue]);
    }
    
    //Get Debt History
    
    for (Debt *tempDebt in debtArray) {
        double debtCompleted = 0;
        NSArray *tempDebtHistoryArray = [DataBaseAccess getAllDebtHistoryInDebt:tempDebt];
        if ([tempDebtHistoryArray count] > 0) {
            for (DebtHistory *debtHistory in tempDebtHistoryArray) {
                debtCompleted += [debtHistory.dh_amount doubleValue];
            }
            [debtCompletedArray addObject:[NSNumber numberWithDouble:debtCompleted]];
        } else {
            [debtCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
        
    }
    
    for (NSNumber *number in debtCompletedArray) {
        NSLog(@"K LOAN: %0.2f", [number doubleValue]);
    }
    
    //------------------Add Income Expense Table View + Footer-----------------//
    incomeExpenseTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, 320, 155.5) style:UITableViewStylePlain];
    incomeExpenseTableView.delegate = self;
    incomeExpenseTableView.dataSource = self;
    incomeExpenseTableView.backgroundColor = [UIColor clearColor];
    incomeExpenseTableView.alpha = 0;
    [self.view addSubview:incomeExpenseTableView];
    
    incomeExpenseLoadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [incomeExpenseLoadMoreButton setImage:[UIImage imageNamed:@"footer_button.png"] forState:UIControlStateNormal];
    incomeExpenseLoadMoreButton.frame = CGRectMake(0, 195.5, 320, 30);
    incomeExpenseLoadMoreButton.alpha = 0;
    incomeExpenseLoadMoreButton.backgroundColor = [UIColor clearColor];
    [incomeExpenseLoadMoreButton addTarget:self action:@selector(icEpenseLoadMoreButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:incomeExpenseLoadMoreButton];
    [self.view bringSubviewToFront:incomeExpenseLoadMoreButton];
    
    //-----------------------------------------------------------------------//
    
    //------------------Add Loan Debt Table View + Footer-----------------//
    loanDebtTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 222.5, 320, 157.5) style:UITableViewStylePlain];
    loanDebtTableView.delegate = self;
    loanDebtTableView.dataSource = self;
    loanDebtTableView.backgroundColor = [UIColor clearColor];
    loanDebtTableView.alpha = 0;
    [self.view addSubview:loanDebtTableView];
    
    loanDebtLoadMoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loanDebtLoadMoreButton setImage:[UIImage imageNamed:@"footer_button.png"] forState:UIControlStateNormal];
    loanDebtLoadMoreButton.frame = CGRectMake(0, 379, 320, 30);
    loanDebtLoadMoreButton.backgroundColor = [UIColor clearColor];
    loanDebtLoadMoreButton.alpha = 0;
    [loanDebtLoadMoreButton addTarget:self action:@selector(loDebtLoadMoreButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loanDebtLoadMoreButton];
    [self.view bringSubviewToFront:loanDebtLoadMoreButton];
    
    //-----------------------------------------------------------------------//
    

    //----------------Fade In Table View And Load More Button---------//
    [UIView animateWithDuration:0.5 animations:^{
        incomeExpenseTableView.alpha = 1;
        incomeExpenseLoadMoreButton.alpha = 1;}
                                completion:^(BOOL finished) {
                                    [UIView animateWithDuration:0.5 animations:^{
                                        loanDebtTableView.alpha = 1;
                                        loanDebtLoadMoreButton.alpha = 1;}];
        
    }];
    
//    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollViewPageChanged) userInfo:nil repeats:YES];
    
    //---------------------------NSNotification Center----------------------//
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewIncomePressed :) name:@"alertViewIncomePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewExpensePressed :) name:@"alertViewExpensePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewReceivePressed :) name:@"alertViewReceivePressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertViewPayPressed :) name:@"alertViewPayPressed" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadIncomeExpenseTable :) name:@"reloadIncomeExpenseTable" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addExpense_OnSuccess :) name:@"addExpense_OnSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLoan_OnSuccess :) name:@"addLoan_OnSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addDebt_OnSuccess :) name:@"addDebt_OnSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(planCompleted : ) name:@"planCompleted" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addLoanDebtHistory_onSuccess : ) name:@"addLoanDebtHistory_onSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadLoanDebtFromDetail : ) name:@"reloadLoanDebtFromDetail" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadIncomeExpenseFromDetail : ) name:@"reloadIncomeExpenseFromDetail" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomeAdded : ) name:@"incomeAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(expenseAdded : ) name:@"expenseAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loanAdded : ) name:@"loanAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(debtAdded : ) name:@"debtAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loanCompleted : ) name:@"loanCompleted" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(debtCompleted : ) name:@"debtCompleted" object:nil];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated {
    //[self viewDidLoad];
    //[[[self navigationController] tabBarController] tabBar].hidden = NO;
    //self.hidesBottomBarWhenPushed = NO;
}
- (void)viewDidUnload
{
    [self setScrollView:nil];
    [self setPopUpView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - IBAction Delegate
- (IBAction)backButtonPressed:(id)sender {
   folyAppDelegate *myDelegate =   (folyAppDelegate *)[[UIApplication sharedApplication]delegate];
    [myDelegate.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)addButtonPressed:(id)sender {
    alertView = [[CustomAlertView alloc]initWithNibName:@"CustomAlertView" bundle:nil];
    
    [self.view addSubview:alertView.view];
    NSLog(@"%@", [self.view subviews]);
}

- (IBAction)editButtonPressed:(id)sender {
    if (tableWithClick == 1) {
        if(currentIndexPath.row < incomeRowNumber) {
            AddIncomeViewController *addIncomeView = [[AddIncomeViewController alloc]init];
            addIncomeView.kindOfView = @"Edit";
            addIncomeView.currentIncome = currentIncome;
            [self.navigationController pushViewController:addIncomeView animated:YES];
        } else {
            AddExpenseViewController *addExpenseView = [[AddExpenseViewController alloc]init];
            addExpenseView.kindOfView = @"Edit";
            addExpenseView.currentExpense = currentExpense;
            [self.navigationController pushViewController:addExpenseView animated:YES];
        }
    } else if (tableWithClick == 2) {
        if (currentIndexPath.row < loanRowNumber) {
            AddLoanViewController *addLoanView = [[AddLoanViewController alloc] init];
            addLoanView.kindOfView = @"Edit";
            addLoanView.currentLoan = currentLoan;
            [self.navigationController pushViewController:addLoanView animated:YES];
        } else {
            AddDebtViewController *addDebtView = [[AddDebtViewController alloc] init];
            addDebtView.kindOfView = @"Edit";
            addDebtView.currentDebt = currentDebt;
            [self.navigationController pushViewController:addDebtView animated:YES];
        }
    }
    
    [popup dismissModal];
    
}

- (IBAction)deleteButtonPressed:(id)sender {
    NSLog(@"%d|%d", currentIndexPath.section, currentIndexPath.row);
    folyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    double walletBalance = [delegate.currentWallet.w_balance doubleValue];

    if (tableWithClick == 1) {
        if(currentIndexPath.row < incomeRowNumber) {
            Income *tempIncome = [incomeArray objectAtIndex:currentIndexPath.row];
            double balance = walletBalance - [tempIncome.i_amount doubleValue];
            NSString *name = tempIncome.i_name;
            if ( balance < 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your wallet is not enough money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [popup dismissModal];
                return;
            } else {
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:balance];
                [DataBaseAccess deleteIncome:tempIncome];
                [incomeArray removeObjectAtIndex:currentIndexPath.row];
                incomeRowNumber--;
                [AJNotificationView showNoticeInView:self.view
                                                type:AJNotificationTypeBlue
                                               title:[NSString stringWithFormat:@"%@ has been deleted!",name]
                                     linedBackground:AJLinedBackgroundTypeDisabled
                                           hideAfter:3.0f];
            }
        } else {
            Expense *tempExpense = [expenseArray objectAtIndex:currentIndexPath.row -incomeRowNumber];
            double balance = walletBalance + [tempExpense.e_amount doubleValue];
            delegate.currentWallet.w_balance = [NSNumber numberWithDouble:balance];
            NSString *name = tempExpense.e_name;
            [DataBaseAccess deleteExpense:tempExpense];
            [expenseArray removeObjectAtIndex:currentIndexPath.row-incomeRowNumber];
            expenseRowNumber--;
            [AJNotificationView showNoticeInView:self.view
                                            type:AJNotificationTypeBlue
                                           title:[NSString stringWithFormat:@"%@ has been deleted!",name]
                                 linedBackground:AJLinedBackgroundTypeDisabled
                                       hideAfter:3.0f];
        }
        [incomeExpenseTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
    } else if (tableWithClick == 2) {
        if (currentIndexPath.row < loanRowNumber) {
            Loan *tempLoan = [loanArray objectAtIndex:currentIndexPath.row];
            NSString *name = tempLoan.l_name;
            if (!tempLoan.l_finished) {
                double completed = [[loanCompletedArray objectAtIndex:currentIndexPath.row] doubleValue];
                double balance = walletBalance + ([tempLoan.l_amount doubleValue] - completed);
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:balance];
            }
            
            [DataBaseAccess deleteLoan:[loanArray objectAtIndex:currentIndexPath.row]];
            [loanArray removeObjectAtIndex:currentIndexPath.row];
            loanRowNumber--;
            [AJNotificationView showNoticeInView:self.view
                                            type:AJNotificationTypeBlue
                                           title:[NSString stringWithFormat:@"%@ has been deleted!",name]
                                 linedBackground:AJLinedBackgroundTypeDisabled
                                       hideAfter:3.0f];
        } else {
            Debt *tempDebt = [debtArray objectAtIndex:currentIndexPath.row - loanRowNumber];
            NSString *name = tempDebt.d_name;
            double balance;
            if (!tempDebt.d_finished) {
                double completed = [[debtCompletedArray objectAtIndex:currentIndexPath.row - [loanArray count]] doubleValue];
                balance = walletBalance - ([tempDebt.d_amount doubleValue] - completed);
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:balance];
            }
            if (balance < 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your wallet is not enough money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [popup dismissModal];
                return;
            } else {
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:balance];
                [DataBaseAccess deleteDebt:[debtArray objectAtIndex:currentIndexPath.row - loanRowNumber]];
                [debtArray removeObjectAtIndex:currentIndexPath.row-loanRowNumber];
                debtRowNumber--;
                [AJNotificationView showNoticeInView:self.view
                                                type:AJNotificationTypeBlue
                                               title:[NSString stringWithFormat:@"%@ has been deleted!",name]
                                     linedBackground:AJLinedBackgroundTypeDisabled
                                           hideAfter:3.0f];
            }
        }
        [loanDebtTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
    }
    
    
    [popup dismissModal];
      
}

- (IBAction)viewButtonPressed:(id)sender {
    if (tableWithClick == 1) {
        if(currentIndexPath.row < incomeRowNumber) {
            ViewIncomeViewController *viewIncomeViewController = [[ViewIncomeViewController alloc]init];
            viewIncomeViewController.currentIncome = currentIncome;
            [self.navigationController pushViewController:viewIncomeViewController animated:YES];
        } else {
            ViewExpenseViewController *viewExpenseViewController = [[ViewExpenseViewController alloc]init];
            viewExpenseViewController.currentExpense = currentExpense;
            [self.navigationController pushViewController:viewExpenseViewController animated:YES];
        }
    } else  if (tableWithClick == 2) {
        if(currentIndexPath.row < loanRowNumber) {
            ViewLoanViewController *viewLoanViewController = [[ViewLoanViewController alloc]init];
            viewLoanViewController.currentLoan = currentLoan;
            [self.navigationController pushViewController:viewLoanViewController animated:YES];
        } else {
            ViewDebtViewController *viewDebtViewController = [[ViewDebtViewController alloc]init];
            viewDebtViewController.currentDebt = currentDebt;
            [self.navigationController pushViewController:viewDebtViewController animated:YES];
        }
    }
    
    
    [popup dismissModal];
}

- (IBAction)payButtonPressed:(id)sender {
    payHistoryAlertView = [[PayHistoryAlertView alloc]initWithNibName:@"PayHistoryAlertView" bundle:nil];
    
    if (tableWithClick == 2) {
        if(currentIndexPath.row < loanRowNumber) {
            payHistoryAlertView.payType = 1;
            payHistoryAlertView.currentLoan = currentLoan;
        } else {
            payHistoryAlertView.payType = 2;
            payHistoryAlertView.currentDebt = currentDebt;
        }
    }
    
    [self.view addSubview:payHistoryAlertView.view];
    NSLog(@"%@", [self.view subviews]);
    [popup dismissModal];
}


-(void) icEpenseLoadMoreButtonPressed{
    IncomeExpenseDetailViewController *detailViewController = [[IncomeExpenseDetailViewController alloc]init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}

-(void) loDebtLoadMoreButtonPressed{
    LoanDebtDetailViewController *detailViewController = [[LoanDebtDetailViewController alloc]init];
    
    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}



#pragma mark - Notification Center Delegate
- (void) alertViewIncomePressed : (NSNotification *) notification {
    AddIncomeViewController *addIncomeViewController = [[AddIncomeViewController alloc]init];
    addIncomeViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addIncomeViewController animated:YES];
}

- (void) alertViewExpensePressed : (NSNotification *) notification {
    AddExpenseViewController *addExpenseViewController = [[AddExpenseViewController alloc]init];
    addExpenseViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addExpenseViewController animated:YES];
}

-(void) alertViewReceivePressed : (NSNotification*) notification {
    AddLoanViewController *addLoanViewController = [[AddLoanViewController alloc]init];
    addLoanViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addLoanViewController animated:YES];
}

-(void) alertViewPayPressed : (NSNotification*) notification {
    AddDebtViewController *addDebtViewController = [[AddDebtViewController alloc]init];
    addDebtViewController.kindOfView = @"Add";
    [self.navigationController pushViewController:addDebtViewController animated:YES];
}

-(void)reloadIncomeExpenseTable: (NSNotification*)notification {
    //folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    //allDateSection = [DataBaseAccess getAllDate:delegate.currentWallet];
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    incomeRowNumber = [incomeArray count];
    NSLog(@"reload income count %d", incomeRowNumber);
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    expenseRowNumber = [expenseArray count];
    
    [incomeExpenseTableView reloadData];
}


-(void) planCompleted : (NSNotification*) notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"Congratulation ! \n %@ has completed",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void) addExpense_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    expenseRowNumber = [expenseArray count];
    
    [incomeExpenseTableView reloadData];
}

-(void) reloadIncomeExpenseFromDetail : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    incomeRowNumber = [incomeArray count];
    expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    expenseRowNumber = [expenseArray count];
    
    [incomeExpenseTableView reloadData];
}

-(void) addLoan_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    debtRowNumber = [debtArray count];
    
    //Get Loan History
    [loanCompletedArray removeAllObjects];
    for (Loan *tempLoan in loanArray) {
        double loanCompleted = 0;
        NSArray *tempLoanHistoryArray = [DataBaseAccess getAllLoanHistoryInLoan:tempLoan];
        if ([tempLoanHistoryArray count] > 0) {
            for (LoanHistory *loanHistory in tempLoanHistoryArray) {
                loanCompleted += [loanHistory.lh_amount doubleValue];
            }
            [loanCompletedArray addObject:[NSNumber numberWithDouble:loanCompleted]];
        } else {
            [loanCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
        
    }
    
    [loanDebtTableView reloadData];
}

-(void) addDebt_OnSuccess : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    debtRowNumber = [debtArray count];
    
    //Get Debt history
    [debtCompletedArray removeAllObjects];
    for (Debt *tempDebt in debtArray) {
        double debtCompleted = 0;
        NSArray *tempDebtHistoryArray = [DataBaseAccess getAllDebtHistoryInDebt:tempDebt];
        if ([tempDebtHistoryArray count] > 0) {
            for (DebtHistory *debtHistory in tempDebtHistoryArray) {
                debtCompleted += [debtHistory.dh_amount doubleValue];
            }
            [debtCompletedArray addObject:[NSNumber numberWithDouble:debtCompleted]];
        } else {
            [debtCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
    }
    
    [loanDebtTableView reloadData];
}

-(void) addLoanDebtHistory_onSuccess : (NSNotification*) notification {
    
    //Get Loan History
    [loanCompletedArray removeAllObjects];
    for (Loan *tempLoan in loanArray) {
        double loanCompleted = 0;
        NSArray *tempLoanHistoryArray = [DataBaseAccess getAllLoanHistoryInLoan:tempLoan];
        if ([tempLoanHistoryArray count] > 0) {
            for (LoanHistory *loanHistory in tempLoanHistoryArray) {
                loanCompleted += [loanHistory.lh_amount doubleValue];
            }
            [loanCompletedArray addObject:[NSNumber numberWithDouble:loanCompleted]];
        } else {
            [loanCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
        
    }
    
    
    //Get Debt History
    [debtCompletedArray removeAllObjects];
    for (Debt *tempDebt in debtArray) {
        double debtCompleted = 0;
        NSArray *tempDebtHistoryArray = [DataBaseAccess getAllDebtHistoryInDebt:tempDebt];
        if ([tempDebtHistoryArray count] > 0) {
            for (DebtHistory *debtHistory in tempDebtHistoryArray) {
                debtCompleted += [debtHistory.dh_amount doubleValue];
            }
            [debtCompletedArray addObject:[NSNumber numberWithDouble:debtCompleted]];
        } else {
            [debtCompletedArray addObject:[NSNumber numberWithDouble:0]];
        }
    }
    
    for (NSNumber *number in debtCompletedArray) {
        NSLog(@"K LOAN: %0.2f", [number doubleValue]);
    }
    
    [loanDebtTableView reloadData];
}

-(void) reloadLoanDebtFromDetail : (NSNotification*)notification {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    loanArray = [DataBaseAccess getAllLoanByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    loanRowNumber = [loanArray count];
    debtArray = [DataBaseAccess getAllDebtByDate:delegate.currentWallet andDateFrom:firstDayOfWeek andDateTo:endDayOfWeek];
    debtRowNumber = [debtArray count];
    
    [loanDebtTableView reloadData];
}

-(void)incomeAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)expenseAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)loanAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)debtAdded : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has added successfully!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

-(void)loanCompleted : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has completed!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}
                                                                          
-(void)debtCompleted : (NSNotification*)notification {
    [AJNotificationView showNoticeInView:self.view
                                    type:AJNotificationTypeBlue
                                   title:[NSString stringWithFormat:@"%@ has completed!",(NSString*)[notification object]]
                         linedBackground:AJLinedBackgroundTypeDisabled
                               hideAfter:3.0f];
}

#pragma mark - Table View Delegate

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//    
//    NSMutableArray *incomeArray = [DataBaseAccess getAllIncomeByDate:delegate.currentWallet andDate:today];
//    NSMutableArray *expenseArray = [DataBaseAccess getAllExpenseByDate:delegate.currentWallet andDate:today];
//    NSLog(@"Number of row %d",[incomeArray count]+[expenseArray count]);
    if (tableView == incomeExpenseTableView) {
        return  [incomeArray count]+[expenseArray count];
    } else if (tableView == loanDebtTableView) {
        return [loanArray count]+[debtArray count];
    }
    return 0;
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {

    return  1;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,320,30)];
    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sub_navbar_bg.png"]];
    //-------------------Format Date Section --------------------//
    
    
    UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 200, 20)];
    if(tableView == incomeExpenseTableView){
        sectionTitleLabel.text = @"Income & Expense Diary";
    } else if (tableView == loanDebtTableView){
        sectionTitleLabel.text = @"Loan & Debt Diary";
    }
        
    
    sectionTitleLabel.textColor = [UIColor whiteColor];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14];
    sectionTitleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:sectionTitleLabel];
    
    return headerView;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellInditifier = @"CellInditifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInditifier] ;
    
    UIImageView *imageView;
    UILabel *titleLabel;
    UITextField *amountTextField;
    UITextField *completedTextField;
    UILabel *dayLabel;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    
    if( cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInditifier];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 40, 40)];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.tag = 100;
        [cell addSubview:imageView];
        
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 10, 200, 20)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor colorWithRed:99.0/255.0 green:182.0/255.0 blue:67.0/255.0 alpha:1];
        titleLabel.tag = 200;
        [cell addSubview:titleLabel];
        
        amountTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 10, 280, 20)];
        amountTextField.textColor = [UIColor whiteColor];
        amountTextField.backgroundColor = [UIColor clearColor];
        amountTextField.font = [UIFont systemFontOfSize:12];
        amountTextField.tag = 300;
        amountTextField.enabled = NO;
        [cell addSubview:amountTextField];
        
        if (tableView == loanDebtTableView) {
            completedTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, 280, 20)];
            completedTextField.textColor = [UIColor whiteColor];
            completedTextField.backgroundColor = [UIColor clearColor];
            completedTextField.font = [UIFont systemFontOfSize:12];
            completedTextField.tag = 400;
            completedTextField.enabled = NO;
            [cell addSubview:completedTextField];
        }
        
        dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 35, 200, 10)];
        dayLabel.backgroundColor = [UIColor clearColor];
        dayLabel.textColor = [UIColor blackColor];
        dayLabel.tag = 500;
        dayLabel.font = [UIFont italicSystemFontOfSize:12.0f];
        [cell addSubview:dayLabel];
    }
    
    imageView = (UIImageView*) [cell viewWithTag:100];
    titleLabel = (UILabel*) [cell viewWithTag:200];
    amountTextField = (UITextField*)[cell viewWithTag:300];
    completedTextField = (UITextField*)[cell viewWithTag:400];
    dayLabel = (UILabel*)[cell viewWithTag:500];
    
    if (tableView == incomeExpenseTableView) {
        if( indexPath.row < [incomeArray count]) {
            Income *tempIncome = [incomeArray objectAtIndex:indexPath.row];
            NSLog(@"%@",tempIncome.i_name);
            titleLabel.text = tempIncome.i_name;
            imageView.image = [UIImage imageNamed:tempIncome.iToIncomeType.it_image];
            
            amountTextField.text = [NSString stringWithFormat:@"%d",[tempIncome.i_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempIncome.i_date];
        } else {
            NSLog(@"indexPath.row = %d",indexPath.row);
            Expense *tempExpense = [expenseArray objectAtIndex:indexPath.row - [incomeArray count]];
            titleLabel.text = tempExpense.e_name;
            imageView.image = [UIImage imageNamed:tempExpense.eToExpenseType.et_image];
            
            amountTextField.text = [NSString stringWithFormat:@"-%d",[tempExpense.e_amount intValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
            dayLabel.text = [dateFormatter stringFromDate:tempExpense.e_date];
        }
    } else if (tableView == loanDebtTableView) {
        if (indexPath.row < [loanArray count]) {
            Loan *tempLoan = [loanArray objectAtIndex:indexPath.row];
            titleLabel.text = tempLoan.l_name;
            if (tempLoan.l_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-money.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempLoan.l_amount floatValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:14.0/255.0 green:154.0/255.0 blue:209.0/255.0 alpha:1];
            
//            if ([loanCompletedArray count] > 0) {
                completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[loanCompletedArray objectAtIndex:indexPath.row] doubleValue]];
//            } else {
//                completedTextField.text = @"0";
//            }
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempLoan.l_date];
        } else {
            Debt *tempDebt = [debtArray objectAtIndex:indexPath.row - [loanArray count]];
            titleLabel.text = tempDebt.d_name;
            if (tempDebt.d_finished == FALSE) {
                imageView.image = [UIImage imageNamed:@"icon-save.png"];
            } else {
                imageView.image = [UIImage imageNamed:@"completed.png"];
                titleLabel.textColor = [UIColor redColor];
            }
            amountTextField.text = [NSString stringWithFormat:@"%0.0f",[tempDebt.d_amount floatValue]];
            amountTextField.borderStyle = UITextBorderStyleRoundedRect;
            amountTextField.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1];
            
//            if ([debtCompletedArray count] != 0) {
                completedTextField.text = [NSString stringWithFormat:@"%0.0f",[[debtCompletedArray objectAtIndex:indexPath.row - [loanArray count]] doubleValue]];
//            } else {
//                completedTextField.text = @"0";
//            }
            
            completedTextField.borderStyle = UITextBorderStyleRoundedRect;
            completedTextField.backgroundColor = [UIColor blackColor];
            
            dayLabel.text = [dateFormatter stringFromDate:tempDebt.d_date];
        }
    }
    
    CGSize amountTextFieldSize = [amountTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    amountTextField.frame = CGRectMake(290-amountTextFieldSize.width,5 , amountTextFieldSize.width+15, 20);
    
    CGSize completedTextFieldSize = [completedTextField.text sizeWithFont:[UIFont systemFontOfSize:12]];
    completedTextField.frame = CGRectMake(290-completedTextFieldSize.width, 25, completedTextFieldSize.width+15, 20);
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    CGRect rectOfCellInTableView;
    CGRect rectOfCellInSuperview;
    
    if (tableView == incomeExpenseTableView) {
        tableWithClick = 1;
        currentIndexPath = indexPath;
        rectOfCellInTableView = [tableView rectForRowAtIndexPath:indexPath];
        rectOfCellInSuperview = [tableView convertRect:rectOfCellInTableView toView:[tableView superview]];
        
        NSLog(@"%d|%d", currentIndexPath.section, currentIndexPath.row);

        NSLog(@"%f %f",rectOfCellInSuperview.origin.x,rectOfCellInSuperview.origin.y);
        if(indexPath.row <incomeRowNumber) {
            currentIncome = [incomeArray objectAtIndex:indexPath.row];
            NSLog(@"%@", incomeArray);
        } else {
            currentExpense = [expenseArray objectAtIndex:indexPath.row-incomeRowNumber];
            NSLog(@"%@", expenseArray);
        }
        
        // Display popup for Income & Expense
        if (popup == nil) {
            popup = [[SNPopupView alloc] initWithContentView:popUpView contentSize:CGSizeMake(170, 60)];
            
            [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
            
            [popup addTarget:self action:@selector(didTouchPopupView:)];
            //[popup release];
            [popup setDelegate:self];
        }
        else if (NO) {
            [popup dismiss:YES];
            popup = nil;
        }
        
    } else if (tableView == loanDebtTableView) {
        tableWithClick = 2;
        currentIndexPath = indexPath; 
        rectOfCellInTableView = [tableView rectForRowAtIndexPath:indexPath];
        rectOfCellInSuperview = [tableView convertRect:rectOfCellInTableView toView:[tableView superview]];
        
        
        NSLog(@"%f %f",rectOfCellInSuperview.origin.x,rectOfCellInSuperview.origin.y);
        if(indexPath.row < loanRowNumber) {
            currentLoan = [loanArray objectAtIndex:indexPath.row];
            NSLog(@"%@", loanArray);
            
            // Display popup for Loan
            if (popup == nil) {
                
                if (currentLoan.l_finished == FALSE) {                    
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];
                //[popup release];
                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        } else {
            currentDebt = [debtArray objectAtIndex:indexPath.row-loanRowNumber];
            NSLog(@"%@", debtArray);
            
            // Display popup for Debt
            if (popup == nil) {
                
                if (currentDebt.d_finished == FALSE) {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];                    
                } else {
                    popup = [[SNPopupView alloc] initWithContentView:popUpViewHistoryFinished contentSize:CGSizeMake(116, 60)];
                }
                
                
                [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
                
                [popup addTarget:self action:@selector(didTouchPopupView:)];
                //[popup release];
                [popup setDelegate:self];
            }
            else if (NO) {
                [popup dismiss:YES];
                popup = nil;
            }
            
        }
        
        // Display popup for Loan & Debt
//        if (popup == nil) {
//            
//            popup = [[SNPopupView alloc] initWithContentView:popUpViewHistory contentSize:CGSizeMake(228, 60)];
//            
//            [popup presentModalAtPoint:CGPointMake(rectOfCellInSuperview.origin.x, rectOfCellInSuperview.origin.y +50) inView:self.view animated:YES];
//            
//            [popup addTarget:self action:@selector(didTouchPopupView:)];
//            //[popup release];
//            [popup setDelegate:self];
//        }
//        else if (NO) {
//            [popup dismiss:YES];
//            popup = nil;
//        }
        
    }
    
    
    
    
}

#pragma mark -----------------Popup-----------------
- (void)didTouchPopupView:(SNPopupView*)sender {
    //	DNSLogMethod
    //	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}


@end
